package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.Service.UserService;
import com.itheima.reggie.common.R;

import com.itheima.reggie.entity.User;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    //RedisTemplate对象，用于操作Redis
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送手机短信验证码  && 手机号对应的验证码保存到Session，方便后续登录时进行比对
     * @param user
     * @return
     */
    //前端传来的用户phone封装到user里的phone
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //获取手机号
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)){
            //utils调用生成验证码 转string方便后续比对
            String code = ValidateCodeUtils.generateValidateCode4String(4);
            log.info("验证码:{}",code);
            //utils调用短信发送验证码
            //SMSUtils.sendMessage("瑞吉外卖","",phone,code);
            //验证码保存到session 传参+Httpsession
            //session.setAttribute(phone,code);


            //需要将生成的验证码保存到Redis,设置过期时间

            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);

            return R.success("验证码发送成功");
        }
        return R.error("验证码发送失败");

    }

    /**
     * 移动端用户登录  UserDto也可以
     * @param map
     * @param session
     * @return
     */
    //前端发送请求json{phone: "   ", code: "   "}  可以用map接收
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session){
        //获取第二次(登录)请求的phone
        String phone = map.get("phone").toString();
        //获取第二次(登录)请求的code
        String code = map.get("code").toString();
        //第一次的code
        //Object codeInSession = session.getAttribute(phone);


        //从Redis中获取缓存的验证码
        Object codeInSession = redisTemplate.opsForValue().get(phone);

        //校验
        if (codeInSession!=null && codeInSession.equals(code)){
            //比对成功 登录   若新用户自动完成注册
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phone);
            User user = userService.getOne(queryWrapper);
            if (user == null){
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);

                userService.save(user);
            }

            //session存key(user) 过滤器getAttribute获取user != null才放行
            session.setAttribute("user",user.getId());


            //从Redis中删除缓存的验证码
            redisTemplate.delete(phone);

            //登陆成功 返回用户信息
            return R.success(user);
        }
        return R.error("登录失败");
    }
    

}